import 'package:flutter/material.dart';

//自定义指示器
class CustomIndicator extends Decoration {
  final double width; //指示器宽度
  final double height; //指示器高度
  final double? topLeft; //指示器圆角
  final double? topRight; //指示器圆角
  final double? bottomLeft; //指示器圆角
  final double? bottomRight; //指示器圆角
  final Color color; //指示器颜色
  final bool useGradient;
  final List<Color> gradientColors;
  final double offsetY;

  CustomIndicator(
      {this.width = 20.0,
      this.height = 3.0,
      this.topLeft = 1,
      this.topRight = 1,
      this.bottomLeft = 1,
      this.bottomRight = 1,
      this.color = Colors.white,
      this.gradientColors = const [Color(0xff84A4F9), Color(0xff2B5DDE)],
      this.useGradient = false,
      this.offsetY = 0});

  @override
  BoxPainter createBoxPainter([VoidCallback? onChanged]) {
    return _CustomBoxPainter(
      this,
      onChanged,
      width,
      height,
      topLeft,
      topRight,
      bottomLeft,
      bottomRight,
      color,
      this.gradientColors,
      this.useGradient,
      this.offsetY,
    );
  }
}

class _CustomBoxPainter extends BoxPainter {
  final CustomIndicator decoration;
  final double indWidth;
  final double indHeight;
  final bool? useGradient;
  final List<Color>? gradientColors;
  final Color color;
  final double? topLeft; //指示器圆角
  final double? topRight; //指示器圆角
  final double? bottomLeft; //指示器圆角
  final double? bottomRight; //指示器圆角
  final double offsetY;

  _CustomBoxPainter(
    this.decoration,
    VoidCallback? onChanged,
    this.indWidth,
    this.indHeight,
    this.topLeft,
    this.topRight,
    this.bottomLeft,
    this.bottomRight,
    this.color,
    this.gradientColors,
    this.useGradient,
    this.offsetY,
  ) : super(onChanged);

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    final size = configuration.size!;
    final newOffset = Offset(
      offset.dx + (size.width - indWidth) / 2,
      size.height - indHeight - offsetY,
    );
    final Rect rect = newOffset & Size(indWidth, indHeight);
    final Paint paint = Paint();
    if (!(useGradient ?? false))
      paint.color = color;
    else
      paint.shader = LinearGradient(
        colors: gradientColors ?? [Color(0xff84A4F9), Color(0xff2B5DDE)],
      ).createShader(rect);
    paint.style = PaintingStyle.fill;
    canvas.drawRRect(
      RRect.fromRectAndCorners(
        rect,
        topLeft: Radius.circular(topLeft ?? 2),
        topRight: Radius.circular(topRight ?? 2),
        bottomLeft: Radius.circular(bottomLeft ?? 2),
        bottomRight: Radius.circular(bottomRight ?? 2),
      ),
      paint,
    );
  }
}
